// Global state to store form data
const appState = {
    businessGoal: '',
    companyName: '',
    industry: '',
    products: '',
    regions: [],
    countries: [],
    marketGoal: '',
    companySize: '',
    businessType: '',
    positions: [],
    keywordsTags: [],
    platforms: ['linkedin', 'google'],
    searchVolume: 20,
    results: [],
    selectedForExport: []
};

// Industry categories mapped to keywords
const industryKeywords = {
    'manufacturing': ['industrial equipment', 'machinery', 'production line', 'factory automation'],
    'electronics': ['electronic components', 'circuit boards', 'IoT devices', 'sensors'],
    'medical': ['medical devices', 'healthcare equipment', 'diagnostic tools', 'surgical supplies'],
    'chemicals': ['chemical products', 'industrial chemicals', 'specialty chemicals'],
    'automotive': ['auto parts', 'car components', 'vehicle manufacturing', 'automotive supplies'],
    'textiles': ['fabrics', 'garments', 'apparel manufacturing', 'textile materials'],
    'furniture': ['furniture manufacturing', 'home furnishings', 'office furniture'],
    'food': ['food processing', 'beverage production', 'packaging solutions'],
    'cosmetics': ['beauty products', 'personal care', 'cosmetic ingredients'],
    'other': ['suppliers', 'wholesalers', 'manufacturers', 'distributors']
};

// Region to countries mapping
const regionCountries = {
    'northamerica': ['United States', 'Canada', 'Mexico'],
    'europe': ['Germany', 'United Kingdom', 'France', 'Italy', 'Spain', 'Netherlands', 'Sweden', 'Poland', 'Switzerland'],
    'asia': ['Japan', 'South Korea', 'China', 'India', 'Singapore', 'Malaysia', 'Thailand', 'Vietnam', 'Indonesia'],
    'oceania': ['Australia', 'New Zealand'],
    'middleeast': ['United Arab Emirates', 'Saudi Arabia', 'Turkey', 'Israel', 'Qatar']
};

// Mock data generator for example lead results
function generateLeads() {
    const industries = ['Manufacturing', 'Electronics', 'Medical Devices', 'Automotive', 'Consumer Goods'];
    const countries = appState.countries.length > 0 ? appState.countries : ['United States', 'Germany', 'Japan', 'United Kingdom', 'France'];
    const sizes = ['Small (10-50)', 'Medium (51-200)', 'Large (201-1000)', 'Enterprise (1000+)'];
    const positions = ['CEO', 'CTO', 'Purchasing Director', 'Operations Manager', 'Marketing Director'];
    
    const leads = [];
    const count = appState.searchVolume;
    
    for (let i = 1; i <= count; i++) {
        // Assign more relevant data based on user selections
        const selectedIndustry = appState.industry ? industryKeywords[appState.industry] : [];
        const relevantIndustry = selectedIndustry.length > 0 ? 
                              appState.industry.charAt(0).toUpperCase() + appState.industry.slice(1) : 
                              industries[Math.floor(Math.random() * industries.length)];
                              
        const relevantCountry = countries[Math.floor(Math.random() * countries.length)];
        const relevantSize = appState.companySize === 'any' ? 
                          sizes[Math.floor(Math.random() * sizes.length)] : 
                          mapCompanySizeToLabel(appState.companySize);
        
        // Generate reasonably realistic company names
        const prefixes = ['Global', 'Advanced', 'Tech', 'Smart', 'Future', 'Prime', 'United', 'Precision', 'Elite', 'Superior'];
        const suffixes = ['Solutions', 'Industries', 'Technologies', 'Innovations', 'Systems', 'International', 'Products', 'Manufacturing'];
        const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        
        let companyName;
        if (Math.random() > 0.3) {
            companyName = `${prefixes[Math.floor(Math.random() * prefixes.length)]} ${suffixes[Math.floor(Math.random() * suffixes.length)]}`;
        } else {
            // Sometimes use abbreviations like "ABC Corp"
            companyName = `${letters.charAt(Math.floor(Math.random() * letters.length))}${letters.charAt(Math.floor(Math.random() * letters.length))}${letters.charAt(Math.floor(Math.random() * letters.length))} Corp`;
        }
        
        const domains = ['.com', '.net', '.co', '.io', '.tech', '.group'];
        const website = `https://www.${companyName.toLowerCase().replace(/\s+/g, '')
            .replace('technologies', 'tech').replace('industries', 'ind').replace('international', 'intl')}${domains[Math.floor(Math.random() * domains.length)]}`;
            
        // Add regional suffixes for authenticity
        const regionSuffixes = {
            'Germany': ' GmbH',
            'United Kingdom': ' Ltd',
            'France': ' SAS',
            'Japan': ' KK',
            'China': ' Co., Ltd',
            'Italy': ' SRL',
            'Spain': ' S.L.',
            'Netherlands': ' B.V.',
        };
        
        if (regionSuffixes[relevantCountry]) {
            companyName += regionSuffixes[relevantCountry];
        }
        
        // Generate relevance score - higher for matching industry and region
        let relevanceScore = 50 + Math.floor(Math.random() * 40);
        if (appState.industry && relevantIndustry.toLowerCase().includes(appState.industry.toLowerCase())) {
            relevanceScore += 10;
        }
        if (appState.regions.length > 0) {
            for (const region of appState.regions) {
                if (regionCountries[region].includes(relevantCountry)) {
                    relevanceScore += 5;
                    break;
                }
            }
        }
        
        // Cap at 95 to make it realistic
        relevanceScore = Math.min(relevanceScore, 95);
        
        // Generate contact person
        const firstNames = ['Michael', 'Robert', 'David', 'John', 'Thomas', 'Sarah', 'Jennifer', 'Laura', 'Emma', 'Maria', 'Zhang', 'Li', 'Hans', 'Klaus', 'Pierre', 'Sophie'];
        const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Miller', 'Wang', 'Chen', 'Mueller', 'Schmidt', 'Dubois', 'Martin', 'Garcia', 'Rossi', 'Tanaka', 'Kim'];
        const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
        const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
        const contactName = `${firstName} ${lastName}`;
        
        // Try to match selected positions
        let contactPosition;
        if (appState.positions.length > 0) {
            const positionMap = {
                'ceo': 'CEO / Managing Director',
                'cto': 'CTO / Technical Director',
                'purchasing': 'Purchasing Manager',
                'operations': 'Operations Director',
                'marketing': 'Marketing Manager'
            };
            const availablePositions = appState.positions.map(p => positionMap[p]);
            contactPosition = availablePositions[Math.floor(Math.random() * availablePositions.length)];
        } else {
            contactPosition = positions[Math.floor(Math.random() * positions.length)];
        }
        
        // Create email from name and company
        const email = `${firstName.toLowerCase()}.${lastName.toLowerCase()}@${website.replace('https://www.', '').split('/')[0]}`;
        
        // Create description based on industry and company
        const descriptions = [
            `Leading provider of ${relevantIndustry.toLowerCase()} solutions with a focus on quality and innovation.`,
            `Established ${relevantIndustry.toLowerCase()} company with global distribution network and strong R&D capabilities.`,
            `Specializes in high-performance ${relevantIndustry.toLowerCase()} products for international markets.`,
            `Innovative ${relevantIndustry.toLowerCase()} firm known for cutting-edge technology and superior service.`,
            `Trusted manufacturer of premium ${relevantIndustry.toLowerCase()} components with over 15 years of industry experience.`
        ];
        const description = descriptions[Math.floor(Math.random() * descriptions.length)];
        
        leads.push({
            id: `LEAD${i.toString().padStart(3, '0')}`,
            company: companyName,
            country: relevantCountry,
            industry: relevantIndustry,
            size: relevantSize,
            contact: {
                name: contactName,
                position: contactPosition,
                email: email,
                phone: `+${Math.floor(Math.random() * 50) + 1} ${Math.floor(Math.random() * 1000) + 100} ${Math.floor(Math.random() * 10000) + 1000}`,
                linkedin: `https://linkedin.com/in/${firstName.toLowerCase()}-${lastName.toLowerCase()}-${Math.floor(Math.random() * 100000)}`
            },
            relevance: relevanceScore,
            description: description,
            website: website,
            source: appState.platforms[Math.floor(Math.random() * appState.platforms.length)]
        });
    }
    
    return leads;
}

// Map company size select values to display labels
function mapCompanySizeToLabel(size) {
    const sizeMap = {
        'small': 'Small (1-50)',
        'medium': 'Medium (51-500)',
        'large': 'Large (501-1000)',
        'enterprise': 'Enterprise (1000+)'
    };
    return sizeMap[size] || 'Not specified';
}

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    initStepNavigation();
    initFormInteractions();
    initSearchStrategy();
    initResultsTable();
});

// Step navigation functionality
function initStepNavigation() {
    const stepItems = document.querySelectorAll('.step-item');
    const stepContents = document.querySelectorAll('.step-content');
    const stepLines = document.querySelectorAll('.step-line');
    
    function goToStep(stepNumber) {
        // Hide all steps
        stepContents.forEach(content => content.classList.add('hidden'));
        
        // Show the selected step
        const targetStep = document.getElementById(`step-${stepNumber}`);
        if (targetStep) targetStep.classList.remove('hidden');
        
        // Update step indicators
        stepItems.forEach((item, index) => {
            const itemStep = parseInt(item.dataset.step);
            if (itemStep < stepNumber) {
                item.classList.add('completed');
                item.querySelector('.step-circle').innerHTML = '✓';
                item.querySelector('.step-circle').classList.add('bg-black', 'text-white');
                if (index < stepLines.length) {
                    stepLines[index].classList.add('active', 'bg-black');
                }
            } else if (itemStep === stepNumber) {
                item.classList.add('active');
                item.querySelector('.step-circle').classList.add('bg-black', 'text-white');
                if (index > 0 && index <= stepLines.length) {
                    stepLines[index-1].classList.add('active', 'bg-black');
                }
            } else {
                item.classList.remove('active', 'completed');
                item.querySelector('.step-circle').innerHTML = itemStep;
                item.querySelector('.step-circle').classList.remove('bg-black', 'text-white');
                if (index < stepLines.length) {
                    stepLines[index].classList.remove('active', 'bg-black');
                }
            }
        });
    }
    
    // Button event listeners for navigation
    document.getElementById('step1Next').addEventListener('click', () => {
        // Collect data from step 1
        appState.companyName = document.getElementById('companyName').value;
        appState.industry = document.getElementById('industry').value;
        appState.products = document.getElementById('products').value;
        
        if (!appState.companyName || !appState.industry) {
            alert('请填写必要的公司信息');
            return;
        }
        
        const goalCards = document.querySelectorAll('.business-goal-card.selected');
        if (goalCards.length === 0) {
            alert('请选择至少一个业务目标');
            return;
        }
        
        goToStep(2);
    });
    
    document.getElementById('step2Prev').addEventListener('click', () => goToStep(1));
    document.getElementById('step2Next').addEventListener('click', () => {
        // Validate region selection
        if (appState.regions.length === 0) {
            alert('请选择至少一个目标地区');
            return;
        }
        
        appState.marketGoal = document.getElementById('marketGoal').value;
        goToStep(3);
    });
    
    document.getElementById('step3Prev').addEventListener('click', () => goToStep(2));
    document.getElementById('step3Next').addEventListener('click', () => {
        // Collect data from step 3
        appState.companySize = document.getElementById('companySize').value;
        appState.businessType = document.getElementById('businessType').value;
        
        const keywordsInput = document.getElementById('keywordsTags').value;
        if (keywordsInput) {
            appState.keywordsTags = keywordsInput.split(',').map(k => k.trim());
        }
        
        // Validate position selection
        if (appState.positions.length === 0) {
            alert('请选择至少一个目标决策者职位');
            return;
        }
        
        updateSearchStrategy();
        goToStep(4);
    });
    
    document.getElementById('step4Prev').addEventListener('click', () => goToStep(3));
    document.getElementById('step4Next').addEventListener('click', () => {
        // Start the search process (simulated)
        startSearch();
        goToStep(5);
    });
    
    document.getElementById('startOver').addEventListener('click', () => goToStep(1));
}

// Form interactions initialization
function initFormInteractions() {
    // Business goal card selection
    const businessGoalCards = document.querySelectorAll('.business-goal-card');
    businessGoalCards.forEach(card => {
        card.addEventListener('click', function() {
            businessGoalCards.forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');
            appState.businessGoal = this.querySelector('h4').textContent;
        });
    });
    
    // Region selection
    const regionCheckboxes = document.querySelectorAll('.region-checkbox');
    regionCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const regionId = this.id.split('-')[1];
            const card = this.closest('.region-card');
            
            if (this.checked) {
                card.classList.add('selected');
                if (!appState.regions.includes(regionId)) {
                    appState.regions.push(regionId);
                }
            } else {
                card.classList.remove('selected');
                appState.regions = appState.regions.filter(r => r !== regionId);
            }
            
            updateCountriesSelection();
        });
    });
    
    // Position selection
    const positionCheckboxes = document.querySelectorAll('.position-checkbox');
    positionCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const positionId = this.id.split('-')[1];
            const card = this.closest('.position-card');
            
            if (this.checked) {
                card.classList.add('selected');
                if (!appState.positions.includes(positionId)) {
                    appState.positions.push(positionId);
                }
            } else {
                card.classList.remove('selected');
                appState.positions = appState.positions.filter(p => p !== positionId);
            }
        });
    });
    
    // Platform selection
    const platformCheckboxes = document.querySelectorAll('.platform-checkbox');
    platformCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const platformId = this.id.split('-')[1];
            const card = this.closest('.platform-card');
            
            if (this.checked) {
                card.classList.add('selected');
                if (!appState.platforms.includes(platformId)) {
                    appState.platforms.push(platformId);
                }
            } else {
                card.classList.remove('selected');
                appState.platforms = appState.platforms.filter(p => p !== platformId);
            }
            
            // Show/hide Facebook strategy card
            if (platformId === 'facebook') {
                document.getElementById('facebook-strategy-card').style.display = this.checked ? 'block' : 'none';
            }
            
            updateSearchStrategy();
        });
    });
    
    // Search volume slider
    const searchVolumeSlider = document.getElementById('searchVolume');
    const searchVolumeValue = document.getElementById('searchVolumeValue');
    
    searchVolumeSlider.addEventListener('input', function() {
        const value = this.value;
        searchVolumeValue.textContent = `${value}个潜在客户`;
        appState.searchVolume = parseInt(value);
    });
    
    // Modal close buttons
    document.getElementById('close-modal').addEventListener('click', function() {
        document.getElementById('customer-detail-modal').classList.add('hidden');
    });
    
    document.getElementById('close-detail-modal').addEventListener('click', function() {
        document.getElementById('customer-detail-modal').classList.add('hidden');
    });
    
    // Export CSV button
    document.getElementById('exportCsv').addEventListener('click', function() {
        exportToCSV(appState.results);
    });
    
    // Save and export button
    document.getElementById('saveAndExport').addEventListener('click', function() {
        exportToCSV(appState.results);
    });

    // Sort results dropdown
    document.getElementById('sortResults').addEventListener('change', function() {
        const sortBy = this.value;
        sortResults(sortBy);
    });
}

// Update countries based on selected regions
function updateCountriesSelection() {
    const countriesContainer = document.getElementById('countries-container');
    const countriesGrid = document.getElementById('countries-grid');
    
    if (appState.regions.length > 0) {
        countriesContainer.classList.remove('hidden');
        
        // Clear previous countries
        countriesGrid.innerHTML = '';
        appState.countries = [];
        
        // Add countries for selected regions
        for (const region of appState.regions) {
            if (regionCountries[region]) {
                for (const country of regionCountries[region]) {
                    const countryId = country.replace(/\s+/g, '').toLowerCase();
                    
                    const div = document.createElement('div');
                    div.className = 'country-card border border-gray-200 rounded-lg p-3 cursor-pointer hover:border-black transition-colors';
                    div.innerHTML = `
                        <div class="flex items-center">
                            <input type="checkbox" id="country-${countryId}" class="country-checkbox h-4 w-4 mr-2">
                            <label for="country-${countryId}" class="cursor-pointer">${country}</label>
                        </div>
                    `;
                    
                    countriesGrid.appendChild(div);
                    
                    // Add event listener to new checkbox
                    const checkbox = div.querySelector('.country-checkbox');
                    checkbox.addEventListener('change', function() {
                        const card = this.closest('.country-card');
                        
                        if (this.checked) {
                            card.classList.add('selected');
                            if (!appState.countries.includes(country)) {
                                appState.countries.push(country);
                            }
                        } else {
                            card.classList.remove('selected');
                            appState.countries = appState.countries.filter(c => c !== country);
                        }
                    });
                }
            }
        }
    } else {
        countriesContainer.classList.add('hidden');
    }
}

// Generate and update search strategy based on user inputs
function initSearchStrategy() {
    // Initial search strategy text
    document.getElementById('linkedin-strategy').innerHTML = `<p>请完成前面的步骤，我们将为您生成LinkedIn搜索策略</p>`;
    document.getElementById('google-strategy').innerHTML = `<p>请完成前面的步骤，我们将为您生成Google搜索策略</p>`;
    document.getElementById('facebook-strategy').innerHTML = `<p>请完成前面的步骤，我们将为您生成Facebook/Meta搜索策略</p>`;
}

function updateSearchStrategy() {
    let linkedinStrategy = '';
    let googleStrategy = '';
    let facebookStrategy = '';
    
    const industry = document.getElementById('industry').value;
    const keywords = document.getElementById('keywordsTags').value;
    const positions = appState.positions;
    const regions = appState.regions;
    
    // Build position search terms
    let positionTerms = '';
    if (positions.includes('ceo')) positionTerms += '"CEO" OR "Managing Director" OR "General Manager" OR ';
    if (positions.includes('cto')) positionTerms += '"CTO" OR "Technical Director" OR "R&D Director" OR ';
    if (positions.includes('purchasing')) positionTerms += '"Purchasing Manager" OR "Procurement Director" OR "Sourcing Manager" OR ';
    if (positions.includes('operations')) positionTerms += '"Operations Director" OR "Production Manager" OR "Supply Chain Manager" OR ';
    if (positions.includes('marketing')) positionTerms += '"Marketing Director" OR "Business Development Manager" OR "Sales Manager" OR ';
    
    // Remove trailing " OR " if any
    if (positionTerms.endsWith(' OR ')) {
        positionTerms = positionTerms.slice(0, -4);
    }
    
    // Get industry keywords
    let industryKeywordsStr = '';
    if (industry && industryKeywords[industry]) {
        industryKeywordsStr = industryKeywords[industry].join('" OR "');
    }
    
    // Add user keywords if provided
    if (keywords.trim()) {
        const userKeywords = keywords.split(',').map(k => k.trim()).join('" OR "');
        industryKeywordsStr += industryKeywordsStr ? ` OR "${userKeywords}"` : `"${userKeywords}"`;
    }
    
    // Get region terms
    let regionTerms = '';
    for (const region of regions) {
        if (regionCountries[region]) {
            regionTerms += regionCountries[region].join('" OR "');
            regionTerms += '" OR "';
        }
    }
    
    // Remove trailing " OR " if any
    if (regionTerms.endsWith(' OR ')) {
        regionTerms = regionTerms.slice(0, -5);
    }
    
    // Build LinkedIn strategy
    if (industryKeywordsStr && positionTerms) {
        linkedinStrategy = `
            <p><strong>搜索语法:</strong></p>
            <pre class="bg-gray-100 p-2 rounded-md mt-1 overflow-x-auto font-geist-mono text-xs">
(${positionTerms}) AND ("${industryKeywordsStr}") ${regionTerms ? `AND ("${regionTerms}")` : ''} -intern -student</pre>
            <p class="mt-2"><strong>搜索策略:</strong></p>
            <ul class="list-disc pl-5 mt-1 text-sm">
                <li>目标人群精确定位，同时覆盖多个相关职位</li>
                <li>使用AND运算符确保同时满足行业和职位条件</li>
                <li>通过排除词(-intern -student)提高目标准确性</li>
                ${appState.companySize !== 'any' ? '<li>根据公司规模进一步筛选目标客户</li>' : ''}
            </ul>`;
    }
    
    // Build Google strategy
    if (industryKeywordsStr && positionTerms) {
        googleStrategy = `
            <p><strong>搜索语法:</strong></p>
            <pre class="bg-gray-100 p-2 rounded-md mt-1 overflow-x-auto font-geist-mono text-xs">
site:linkedin.com (${positionTerms.replace(/"/g, '\\"')}) ("${industryKeywordsStr.replace(/"/g, '\\"')}") ${regionTerms ? `("${regionTerms.replace(/"/g, '\\"')}")` : ''} -jobs -hiring</pre>
            <p class="mt-2"><strong>搜索策略:</strong></p>
            <ul class="list-disc pl-5 mt-1 text-sm">
                <li>利用site:指令限定搜索范围到LinkedIn等专业平台</li>
                <li>采用组合关键词提高搜索精度</li>
                <li>通过-jobs/-hiring过滤掉招聘信息，专注于企业和决策者</li>
                <li>可结合filetype:pdf或filetype:ppt搜索行业报告获取目标客户</li>
            </ul>`;
    }
    
    // Build Facebook strategy
    if (industryKeywordsStr && appState.platforms.includes('facebook')) {
        facebookStrategy = `
            <p><strong>搜索策略:</strong></p>
            <ul class="list-disc pl-5 mt-1 text-sm">
                <li>定位相关行业专业群组和行业协会页面</li>
                <li>分析行业展会和活动页面的互动用户</li>
                <li>通过竞争对手页面粉丝分析找到潜在客户</li>
                <li>使用Facebook广告库(fb.com/ads/library)分析竞争对手广告受众</li>
            </ul>`;
    }
    
    // Update the strategy displays
    document.getElementById('linkedin-strategy').innerHTML = linkedinStrategy || '<p>请完成所有必要信息以生成LinkedIn搜索策略</p>';
    document.getElementById('google-strategy').innerHTML = googleStrategy || '<p>请完成所有必要信息以生成Google搜索策略</p>';
    document.getElementById('facebook-strategy').innerHTML = facebookStrategy || '<p>请完成所有必要信息以生成Facebook搜索策略</p>';
}

// Simulate the search process
function startSearch() {
    const progressBar = document.getElementById('progress-bar');
    const progressPercentage = document.getElementById('progress-percentage');
    const loadingResults = document.getElementById('loading-results');
    const resultsContainer = document.getElementById('results-container');
    
    // Show loading, hide results
    loadingResults.classList.remove('hidden');
    resultsContainer.classList.add('hidden');
    
    // Animate progress bar
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 5;
        if (progress > 100) progress = 100;
        
        progressBar.style.width = `${progress}%`;
        progressPercentage.textContent = `${Math.floor(progress)}%`;
        
        if (progress >= 100) {
            clearInterval(interval);
            setTimeout(() => {
                // Generate and display results
                appState.results = generateLeads();
                displayResults(appState.results);
                
                // Hide loading, show results
                loadingResults.classList.add('hidden');
                resultsContainer.classList.remove('hidden');
            }, 500);
        }
    }, 200);
}

// Initialize results table functionality
function initResultsTable() {
    // Prepare event listeners for viewing details
    document.addEventListener('click', function(e) {
        if (e.target && e.target.classList.contains('view-details-btn')) {
            const leadId = e.target.dataset.id;
            const lead = appState.results.find(l => l.id === leadId);
            if (lead) {
                showLeadDetails(lead);
            }
        }
    });
    
    // Add to export list button in modal
    document.getElementById('add-to-export').addEventListener('click', function() {
        const leadId = this.dataset.id;
        const lead = appState.results.find(l => l.id === leadId);
        
        if (lead && !appState.selectedForExport.includes(lead.id)) {
            appState.selectedForExport.push(lead.id);
            alert(`已添加到导出列表: ${lead.company}`);
        }
    });
}

// Display search results in the table
function displayResults(leads) {
    const tableBody = document.getElementById('results-table-body');
    const resultsCount = document.getElementById('results-count');
    
    // Clear previous results
    tableBody.innerHTML = '';
    
    // Update count
    resultsCount.textContent = leads.length;
    
    // Add each lead to the table
    leads.forEach(lead => {
        const row = document.createElement('tr');
        
        row.innerHTML = `
            <td class="border-t">
                <div class="font-medium">${lead.company}</div>
                <div class="text-xs text-gray-500">${lead.website}</div>
            </td>
            <td class="border-t">${lead.country}</td>
            <td class="border-t">${lead.industry}</td>
            <td class="border-t">${lead.size}</td>
            <td class="border-t">
                <div>${lead.contact.name}</div>
                <div class="text-xs text-gray-500">${lead.contact.position}</div>
            </td>
            <td class="border-t">
                <div class="flex items-center">
                    <div class="w-16 h-2 bg-gray-200 rounded-full mr-2">
                        <div class="h-2 bg-black rounded-full" style="width: ${lead.relevance}%"></div>
                    </div>
                    <span>${lead.relevance}%</span>
                </div>
            </td>
            <td class="border-t">
                <button data-id="${lead.id}" class="view-details-btn px-3 py-1.5 text-sm rounded-md bg-black text-white hover:bg-gray-800 transition-colors">查看详情</button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
}

// Show detailed information for a specific lead
function showLeadDetails(lead) {
    // Update modal with lead details
    document.getElementById('modal-company-name').textContent = lead.company;
    document.getElementById('modal-company').textContent = lead.company;
    
    const websiteLink = document.getElementById('modal-website');
    websiteLink.href = lead.website;
    websiteLink.textContent = lead.website;
    
    document.getElementById('modal-country').textContent = lead.country;
    document.getElementById('modal-industry').textContent = lead.industry;
    document.getElementById('modal-size').textContent = lead.size;
    
    document.getElementById('modal-contact').textContent = lead.contact.name;
    document.getElementById('modal-position').textContent = lead.contact.position;
    
    const emailLink = document.getElementById('modal-email');
    emailLink.href = `mailto:${lead.contact.email}`;
    emailLink.textContent = lead.contact.email;
    
    const linkedinLink = document.getElementById('modal-linkedin');
    linkedinLink.href = lead.contact.linkedin;
    linkedinLink.textContent = lead.contact.linkedin.replace('https://linkedin.com/in/', '');
    
    document.getElementById('modal-phone').textContent = lead.contact.phone;
    document.getElementById('modal-description').textContent = lead.description;
    
    // Update relevance scoring
    document.getElementById('modal-relevance-bar').style.width = `${lead.relevance}%`;
    document.getElementById('modal-relevance-score').textContent = `${lead.relevance}%`;
    
    // Generate relevance analysis based on score
    let relevanceAnalysis = '';
    if (lead.relevance >= 85) {
        relevanceAnalysis = `高度匹配您的目标客户画像。该公司处于${lead.industry}行业，与您的核心业务高度相关。公司规模适中，${lead.contact.position}是理想的决策者接触点。建议优先跟进。`;
    } else if (lead.relevance >= 70) {
        relevanceAnalysis = `良好匹配您的目标客户。公司业务与您的产品/服务存在明显的契合点，推荐深入了解其具体需求以确定合作可能性。`;
    } else {
        relevanceAnalysis = `基本匹配您的搜索条件。虽然不是最理想的目标客户，但仍有一定的业务潜力。建议在资源允许的情况下跟进。`;
    }
    document.getElementById('modal-relevance-analysis').textContent = relevanceAnalysis;
    
    // Generate outreach strategy recommendation
    let strategy = '';
    if (lead.relevance >= 85) {
        strategy = `<ol class="list-decimal pl-5 space-y-1">
            <li>通过LinkedIn发送个性化连接请求，提及您对${lead.industry}行业的了解和价值主张</li>
            <li>连接成功后，发送一份定制的解决方案简介，针对${lead.company}可能面临的具体挑战</li>
            <li>提议安排15分钟的视频会议，了解他们的需求并展示您的产品/服务</li>
            <li>会议后发送个性化跟进邮件，包含与会议讨论相关的资料</li>
        </ol>`;
    } else if (lead.relevance >= 70) {
        strategy = `<ol class="list-decimal pl-5 space-y-1">
            <li>通过LinkedIn或电子邮件发送初步询问，介绍您的公司并表达合作意愿</li>
            <li>分享相关行业案例研究或白皮书，展示您在${lead.industry}领域的专业知识</li>
            <li>提供免费咨询或产品演示的机会，降低初次接触的门槛</li>
        </ol>`;
    } else {
        strategy = `<ol class="list-decimal pl-5 space-y-1">
            <li>将其添加到您的营销邮件列表，定期分享行业见解和公司动态</li>
            <li>关注其LinkedIn动态，适时互动和评论，建立初步联系</li>
            <li>在行业展会或活动上寻找见面机会，进行面对面交流</li>
        </ol>`;
    }
    document.getElementById('modal-strategy').innerHTML = strategy;
    
    // Set lead ID for export button
    document.getElementById('add-to-export').dataset.id = lead.id;
    
    // Show the modal
    document.getElementById('customer-detail-modal').classList.remove('hidden');
}

// Sort results by different criteria
function sortResults(sortBy) {
    let sortedResults = [...appState.results];
    
    switch (sortBy) {
        case 'relevance':
            sortedResults.sort((a, b) => b.relevance - a.relevance);
            break;
        case 'company':
            sortedResults.sort((a, b) => a.company.localeCompare(b.company));
            break;
        case 'country':
            sortedResults.sort((a, b) => a.country.localeCompare(b.country));
            break;
        default:
            break;
    }
    
    displayResults(sortedResults);
}

// Export results to CSV file
function exportToCSV(leads) {
    // Filter leads if there's a selection for export
    const leadsToExport = appState.selectedForExport.length > 0 ? 
                        leads.filter(l => appState.selectedForExport.includes(l.id)) : 
                        leads;
    
    // Prepare CSV header and rows
    const csvHeader = [
        '公司名称',
        '国家/地区',
        '行业',
        '公司规模', 
        '联系人',
        '职位',
        '电子邮箱',
        '电话',
        'LinkedIn',
        '网站',
        '相关度',
        '业务描述',
        '数据来源'
    ];
    
    const csvRows = [csvHeader];
    
    leadsToExport.forEach(lead => {
        csvRows.push([
            lead.company,
            lead.country,
            lead.industry,
            lead.size,
            lead.contact.name,
            lead.contact.position,
            lead.contact.email,
            lead.contact.phone,
            lead.contact.linkedin,
            lead.website,
            `${lead.relevance}%`,
            lead.description,
            lead.source
        ]);
    });
    
    // Convert to CSV format
    let csvContent = '';
    csvRows.forEach(row => {
        csvContent += row.map(cell => `"${cell}"`).join(',') + '\n';
    });
    
    // Create blob and download
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `潜在客户清单_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
